﻿using Aspose.Cells;
using AWSV2.ViewModels;
using AWSV2.Services;
using Common.AJControls;
using Common.EF.Controllers;
using Common.Model;
using Common.Models;
using Common.Platform;
using Common.Utility;
using Common.Utility.AJ;
using Common.Utility.AJ.Extension;
using Common.Utility.AJ.MobileConfiguration;
using Common.Utility.AJ.MobileConfiguration.WeightSystem;
using Common.ViewModels;
using Masuit.Tools;
using MaterialDesignThemes.Wpf;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json.Linq;
using NPOI.SS.Formula.Functions;
using NPOI.XSSF.UserModel;
using Stylet;
using SUT.PrintEngine.Utils;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Markup;
using System.Windows.Threading;
using static Common.AJControls.AJMultiSelect;
using static Common.Utility.PrintHelper;
using Common;
using Common.Converters;
using System.Windows.Data;

namespace AWSV2.ViewModels
{
    public class WeightListViewModel : Screen
    {
        private bool _viewLoaded;

        private bool _loading;
        public bool Loading
        {
            get => _loading;
            set => SetAndNotify(ref _loading, value);
        }

        #region 日期字段类型筛选 --阿吉 2024年9月6日14点37分

        private string _selectedDateField;
        public string SelectedDateField
        {
            get => _selectedDateField;
            set => SetAndNotify(ref _selectedDateField, value);
        }

        private ObservableCollection<AJMultiSelectOptionItem> _dateFieldOptions;
        public ObservableCollection<AJMultiSelectOptionItem> DateFieldOptions
        {
            get => _dateFieldOptions;
            set => SetAndNotify(ref _dateFieldOptions, value);
        }


        #endregion

        private AJTableImportOptions _importOptions;

        private List<DynamicPoundFieldItem> _importOrExportFields;
        private List<DropdownOption> _fieldsSource;
        private ObservableCollection<DynamicPoundFieldItem> _dyanmicPoundFieldItems;
        public ObservableCollection<DynamicPoundFieldItem> DyanmicPoundFieldItems
        {
            get
            {
                return _dyanmicPoundFieldItems;
            }
            set
            {
                SetAndNotify(ref _dyanmicPoundFieldItems, value);
            }
        }

        private bool? _dyanmicPoundFieldDisplayAllChecked;
        public bool? DyanmicPoundFieldDisplayAllChecked
        {
            get
            {
                return _dyanmicPoundFieldDisplayAllChecked;
            }
            set
            {
                if (SetAndNotify(ref _dyanmicPoundFieldDisplayAllChecked, value))
                {
                    if (DyanmicPoundFieldItems?.Count > 0)
                    {
                        if (value == null)
                        {
                            return;
                        }
                        foreach (var item in DyanmicPoundFieldItems)
                        {
                            item.IsColumnDisplay = value.GetValueOrDefault();
                        }
                    }
                }
            }
        }

        public void ColumnDisplayCheckChanged(object sender, System.Windows.RoutedEventArgs e)
        {
            if (DyanmicPoundFieldItems.Count(p => p.IsColumnDisplay) == 0)
            {
                DyanmicPoundFieldDisplayAllChecked = false;
                return;
            }
            if (DyanmicPoundFieldItems.Count(p => p.IsColumnDisplay) == DyanmicPoundFieldItems.Count)
            {
                DyanmicPoundFieldDisplayAllChecked = true;
                return;
            }
            DyanmicPoundFieldDisplayAllChecked = null;
        }


        private IWindowManager windowManager;

        public string SearchText { get; set; }

        private string dateFilter; //日期筛选，0：本日 1：本月 2：自定义
        public string DateFilter
        {
            get
            {
                return dateFilter;
            }
            set
            {
                dateFilter = value;
                if (value.Equals("0"))
                {
                    StartDate = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd"));
                    EndDate = Convert.ToDateTime(DateTime.Now.AddDays(1).ToString("yyyy-MM-dd").ToString()).AddSeconds(-1);
                }
                else if (value.Equals("1"))
                {
                    StartDate = DateTime.Now.AddDays(1 - DateTime.Now.Day).Date;
                    EndDate = DateTime.Now.AddDays(1 - DateTime.Now.Day).Date.AddMonths(1).AddSeconds(-1);
                }
            }
        }
        private DateTime? _startDate;
        public DateTime? StartDate
        {
            get => _startDate;
            set => SetAndNotify(ref _startDate, value);
        }

        private DateTime? _endDate;
        public DateTime? EndDate
        {
            get => _endDate;
            set => SetAndNotify(ref _endDate, value);
        }

        /// <summary>
        /// 重新上传按钮可见性 --阿吉 2023年7月14日11点35分
        /// </summary>
        public Visibility ReUploadButtonVisible { get; set; } = Visibility.Collapsed;

        public System.Windows.Visibility ButtonVisible { get; set; } = System.Windows.Visibility.Visible;//当选中删除的记录时，需要将其他的按钮隐藏的标记
        public string DelBtnText { get; set; } = I18NService.Translate(LangKeys.作废选中);//当选中了删除数据后，这个文本就要变成“取消作废”，当选择的是正常的数据时，这个文本就是“作废选中”。
        public string UnfinishedReportData { get; set; }
        public string ReportData { get; set; }

        private WeighingRecord _selectedRowRecord;
        /// <summary>
        /// 选中的称重记录行，补充打印用
        /// </summary>
        public WeighingRecord SelectedRowRecord
        {
            get => _selectedRowRecord;
            set => SetAndNotify(ref _selectedRowRecord, value);
        }

        private ObservableCollection<WeighingRecord> _weighintRecordRows;
        /// <summary>
        /// 从数据库中查询出的原始称重记录
        /// </summary>
        public ObservableCollection<WeighingRecord> WeighingRecordRows
        {
            get => _weighintRecordRows;
            set => SetAndNotify(ref _weighintRecordRows, value);
        }

        /// <summary>
        /// 用来存放导出逻辑导出的数据行,计算总计行使用 --阿吉 2025年2月17日14点57分
        /// </summary>
        private List<Common.Models.WeighingRecord> _tempExportedRows;

        public int SelectedTotalWeighingCount { get; private set; }

        public string WeighingUnit { get; }


        private bool selectAll;
        public bool SelectAll
        {
            get
            {
                return selectAll;
            }
            set
            {
                selectAll = value;
                // SetAndNotify(ref selectAll, value);
            }
        }

        private CheckBox _allRowCheckbox;
        private bool _allRowCheckboxProcess;

        private DispatcherTimer autoCheckTimer = new DispatcherTimer();

        private bool autoCheck;
        public bool AutoCheck
        {
            get { return autoCheck; }
            set
            {
                autoCheck = value;

                if (value)
                {
                    autoCheckTimer.Start();
                }
                else
                {
                    autoCheckTimer.Stop();
                }
            }
        }


        private int _weightValueDisplayFormat;
        public int WeightValueDisplayFormat
        {
            get
            {
                return _weightValueDisplayFormat;
            }
            set
            {
                SetAndNotify(ref _weightValueDisplayFormat, value);
            }
        }

        private string _currentLoginId;
        public string CurrentLoginId { get => _currentLoginId; set => SetAndNotify(ref _currentLoginId, value); }

        private string _platformName;

        public List<Common.Models.WeighingRecord> NotUploadedRecords { get; set; }

        private AppSettingsSection _mainSettings;

        public void RefreshPage()
        {
            if (DyanmicPoundFieldItems == null)
            {
                return;
            }
            Query();
        }

        private bool _isFinished;

        public WeightListViewModel(IWindowManager windowManager, bool isFinished)
        {
            _tempExportedRows = new List<WeighingRecord>();
            _isFinished = isFinished;
            CurrentLoginId = Globalspace._currentUser.LoginId;
            _mainSettings = Common.Utility.SettingsHelper.AWSV2Settings;
            _platformName = _mainSettings.Settings["PlatformName"].TryGetString("Default");
            Common.Platform.PlatformManager.Instance.Init(_platformName);
            Common.LPR.LPRService.LPRSavePath = _mainSettings.Settings["LPRSavePath"].TryGetString();

            this.windowManager = windowManager;
            //初始化日期筛选选择本日
            DateFilter = "0";

            WeighingUnit = _mainSettings.Settings["WeighingUnit"].TryGetString();

            WeightValueDisplayFormat = _mainSettings.Settings[nameof(WeightValueDisplayFormat)].TryGetInt(1);

            var pageSizeItems = new List<ComboItem>();
            var sizeArray = new int[] { 10, 100, 500, 1000, 2000, 5000, 10000 };
            foreach (var size in sizeArray)
            {
                pageSizeItems.Add(new ComboItem
                {
                    Name = I18NService.Translate(LangKeys._0_条每页, size),
                    Value = size
                });
            }
            PageSizeItems = new ObservableCollection<ComboItem>(pageSizeItems);
        }

        public void OpenExportDialog()
        {
            _tempExportedRows.Clear();
            using var ctrl = new WeighingRecordController();
            var mapper = AJAutoMapperService.Instance().Mapper;
            var query = CreateWeighingRecordSearchForm();
            _ = windowManager.ShowDialog(new AJExportDialogViewModel(
                I18NService.Translate(LangKeys._0_导出__1_, I18NService.Translate(LangKeys.称重记录), DateTime.Now.ToString("yyyyMMdd_HHmm")),
                    (pageCfg) =>
                    {
                        query.Page = pageCfg.Current;
                        query.Limit = pageCfg.PageSize;
                        return Task.Run(async () =>
                        {
                            var paged = await ctrl.Pages(query);

                            var pageRows = mapper.Map<List<Common.EF.Tables.WeighingRecord>, List<Common.Models.WeighingRecord>>(paged.Data);
                            _tempExportedRows.AddRange(pageRows);

                            var rows = pageRows
                                .Select(p => WeighingRecordExcelModel.Convert(p, _importOrExportFields)).ToList();

                            return new AJTableFetchResult
                            {
                                HasNext = paged.HasNext,
                                Total = paged.TotalCount,
                                Rows = rows
                            };
                        });
                    },
                    (_, __) =>
                    {
                        object result;
                        var model = new WeighingRecordExcelModel();
                        var totalSumRow = new Dictionary<string, string>();

                        var label1 = _importOrExportFields.ElementAtOrDefault(0)?.Label ?? $"_1";
                        var label2 = _importOrExportFields.ElementAtOrDefault(1)?.Label ?? $"_2";
                        var label3 = _importOrExportFields.ElementAtOrDefault(2)?.Label ?? $"_3";
                        var label4 = _importOrExportFields.ElementAtOrDefault(3)?.Label ?? $"_4";
                        var label5 = _importOrExportFields.ElementAtOrDefault(4)?.Label ?? $"_5";
                        var label6 = _importOrExportFields.ElementAtOrDefault(5)?.Label ?? $"_6";

                        totalSumRow.Add(label1, $"{I18NService.Translate(LangKeys.当页未完成_0_, _tempExportedRows.Count(p => !p.IsFinish))}");
                        totalSumRow.Add(label2, $"{I18NService.Translate(LangKeys.当页总扣重_0_, AJUtil.ChineseRound(_tempExportedRows.Sum(p => p.Kz)))}");
                        totalSumRow.Add(label3, $"{I18NService.Translate(LangKeys.当页总皮重_0_, AJUtil.ChineseRound(_tempExportedRows.Sum(p => p.Pz)))}");
                        totalSumRow.Add(label4, $"{I18NService.Translate(LangKeys.当页总毛重_0_, AJUtil.ChineseRound(_tempExportedRows.Sum(p => p.Mz)))}");
                        totalSumRow.Add(label5, $"{I18NService.Translate(LangKeys.当页总净重_0_, AJUtil.ChineseRound(_tempExportedRows.Sum(p => p.Jz)))}");
                        totalSumRow.Add(label6, $"{I18NService.Translate(LangKeys.当页总实重_0_, AJUtil.ChineseRound(_tempExportedRows.Sum(p => p.Sz)))}");


                        model.DynamicColumns = totalSumRow;
                        result = model;
                        return Task.FromResult(result);
                    }
                ));
        }

        public void OpenImportDialog()
        {
            bool? result = windowManager.ShowDialog(new ImportExcelDialogViewModel(_importOptions));

            if (result.GetValueOrDefault(true))
            {
                QueryList();
            }
        }

        protected override async void OnViewLoaded()
        {
            if (_viewLoaded)
            {
                return;
            }
            var isDefaultPlatform = _platformName.Equals("default", StringComparison.OrdinalIgnoreCase);

            if (!isDefaultPlatform)
            {
                using var db = AJDatabaseService.GetDbContext();
                var pages = await db.WeighingRecords.Where(p => p.IsUpload == false).ToListAsync();

                NotUploadedRecords = AJAutoMapperService.Instance().Mapper.Map<List<Common.EF.Tables.WeighingRecord>, List<Common.Models.WeighingRecord>>(pages);
            }

            ReUploadButtonVisible = !isDefaultPlatform && NotUploadedRecords.Count > 0
                 ? Visibility.Visible : Visibility.Collapsed;

            var pound = new PoundCfg();
            var mgr = new MobileConfigurationMgr(true)
            {
                WeightFormTemplatePath = Globalspace._weightFormTemplatePath
            };

            Loading = true;

            _fieldsSource = await pound.InitFieldsAsync(mgr, true);

            Loading = false;

            var allDyanmicPoundFieldItems = Common.Models.WeighingRecord
                .GetDyanmicPoundFieldItems(_mainSettings, true, true);

            var entryTimeField = nameof(Common.Models.WeighingRecord.EntryTime);
            var finishedField = nameof(Common.Models.WeighingRecord.IsFinish);
            var dateFields = Common.Models.WeighingRecord.GetWeightWeighDateFields();

            DateFieldOptions = new ObservableCollection<AJMultiSelectOptionItem>(dateFields
                .Select(p => new AJMultiSelectOptionItem
                {
                    Label = allDyanmicPoundFieldItems.FirstOrDefault(q => q.Field == p)?.Label ?? p,
                    Value = p
                }));

            SelectedDateField = _isFinished
                ? DateFieldOptions.FirstOrDefault().Value as string
                : DateFieldOptions.ElementAtOrDefault(1).Value as string;

            var by20Field = nameof(Common.Models.WeighingRecord.By20);
            DyanmicPoundFieldItems = new ObservableCollection<DynamicPoundFieldItem>(_fieldsSource
                .Where(p => p.key != entryTimeField && p.key != finishedField)
                .Select(p => new DynamicPoundFieldItem
                {
                    Field = p.key,
                    Label = p.value.ToString(),
                    FormType = p.formType,
                    IsFilterDisplay = p.key != by20Field && !dateFields.Contains(p.key),
                    IsColumnDisplay = p.key != by20Field,
                    Options = p.children?.Count > 0
                    ? new ObservableCollection<AJMultiSelectOptionItem>(p.children.Select(q => new AJMultiSelectOptionItem
                    {
                        Label = q.label,
                        Value = q.value,
                    }))
                    : new ObservableCollection<AJMultiSelectOptionItem>()
                }));

            _importOrExportFields = DyanmicPoundFieldItems
                           .Where(p => p.IsColumnDisplay && p.Field != by20Field).ToList();

            _importOptions = new AJTableImportOptions
            {
                ImportType = typeof(Common.Models.WeighingRecord),
                IncludeEntityProperties = _importOrExportFields.Select(p => p.Field).ToArray(),
                TemplateRowsHandler = () =>
                {
                    var props = typeof(Common.Models.WeighingRecord).GetRuntimeProperties();
                    var dic = new Dictionary<string, string>();
                    foreach (var prop in props)
                    {
                        var item = _importOrExportFields.FirstOrDefault(p => p.Field == prop.Name);
                        if (item != null)
                        {
                            if (prop.Name == nameof(Common.Models.WeighingRecord.Bh))
                            {
                                dic.Add(item.Label, $"{I18NService.Translate(LangKeys.必填)},{I18NService.Translate(LangKeys.如_0_, "20240001")}");
                                continue;
                            }
                            if (prop.Name == nameof(Common.Models.WeighingRecord.Ch))
                            {
                                dic.Add(item.Label, $"{I18NService.Translate(LangKeys.必填)},{I18NService.Translate(LangKeys.如_0_, "贵A12345")}");
                                continue;
                            }
                            if (prop.PropertyType == typeof(DateTime)
                                || prop.PropertyType == typeof(DateTime?))
                            {
                                dic.Add(item.Label, $"{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}");
                                continue;
                            }

                            if (prop.PropertyType == typeof(decimal))
                            {
                                dic.Add(item.Label, "0");
                                continue;
                            }

                            if (prop.PropertyType == typeof(bool))
                            {
                                dic.Add(item.Label, $"{I18NService.Translate(LangKeys.是)}/{I18NService.Translate(LangKeys.否)}");
                                continue;
                            }
                            dic.Add(item.Label, string.Empty);
                        }
                    }

                    return new List<object> {
                        new Common.Models.WeighingRecordExcelModel
                        {
                            DynamicColumns = dic
                        }
                    };
                },
                ImportDataItemProcessHandler = (rows) =>
                {
                    using var ctrl = new WeighingRecordController();
                    var mapper = AJAutoMapperService.Instance().Mapper;
                    var importForm = new Common.EF.Tables.WeighingRecordImportForm();
                    var rowList = rows.Select(p => (Common.Models.WeighingRecord)p).ToList();
                    var importTask = Task.Run(() =>
                    {
                        importForm.Rows = mapper.Map<List<Common.Models.WeighingRecord>, List<Common.EF.Tables.WeighingRecord>>(rowList);
                        return ctrl.Import(importForm);
                    });
                    importTask.Wait();
                    return importTask.Result;
                },
                ImportCompleteHandler = () =>
                {
                    var result = new ProcessResult();
                    result.SetSuccess();
                    return Task.FromResult(result);
                }

            };

            //初始化分页控件的页行数的大小
            SelectedPageSizeItems = PageSizeItems.FirstOrDefault();

            _viewLoaded = true;

            var worker = new BackgroundWorker();
            worker.DoWork += (_, __) =>
            {
                while (_dataGrid == null)
                {
                    Thread.Sleep(600);
                    continue;
                }
            };
            worker.RunWorkerCompleted += (_, __) =>
            {
                _dataGrid.Dispatcher.Invoke(() =>
                {
                    ReGenerateColumns();
                });
            };
            worker.RunWorkerAsync();
        }

        /// <summary>
        ///  重构称重记录表格列 --阿吉 2025年2月12日14点52分
        /// </summary>
        private void ReGenerateColumns()
        {
            if ((DyanmicPoundFieldItems?.Count).GetValueOrDefault() == 0)
            {
                return;
            }

            var _weighRecordModelProps = typeof(WeighingRecord).GetRuntimeProperties();

            var columns = _dataGrid.Columns.ToList();
            columns.RemoveAll(p => p is AJDataGridDynamicTextColumn);

            _dataGrid.Columns.Clear();

            var customColumns = DyanmicPoundFieldItems.Where(p => p.IsColumnDisplay).OrderBy(p => p.SortNo).ToList();
            var weightValFields = WeighingRecord.GetWeightValueFields();
            foreach (var item in customColumns)
            {
                var prop = _weighRecordModelProps.FirstOrDefault(p => p.Name.Equals(item.Field, StringComparison.OrdinalIgnoreCase));

                if (prop == null)
                {
                    continue;
                }

                var binding = new Binding(prop.Name)
                {
                    Converter = new WeighingRecordRowValueFormatConvert
                    {
                        WeightValueDisplayFormat = WeightValueDisplayFormat
                    },
                    ConverterParameter = item
                };

                columns.Add(new AJDataGridDynamicTextColumn(item)
                {
                    Binding = binding,
                });
            }

            foreach (var item in columns)
            {
                _dataGrid.Columns.Add(item);
            }
        }

        private DataGrid _dataGrid;

        public async void DeleteSelectedRows()
        {
            var records = WeighingRecordRows.Where(p => p.Checked).ToList();

            if (records.Count == 0)
            {
                MessageBox.Show(I18NService.Translate(LangKeys.请先选择要删除的记录));
                return;
            }

            var result = windowManager.ShowDialog(new Common.ViewModels.PasswordViewModel(Globalspace._currentUser.LoginId,
                Common.ViewModels.PasswordConfirmType.用户验证, true));

            var platform = Common.Platform.PlatformManager.Instance.Current as PlatformBase;
            if (result.GetValueOrDefault())
            {
                var deleted = new List<string>();
                using var db = AJDatabaseService.GetDbContext();
                var mapper = AJAutoMapperService.Instance().Mapper;

                foreach (var record in records)
                {
                    if (platform == null)
                    {
                        deleted.Add(record.Bh);
                        continue;
                    }
                    else
                    {
                        var deleteResult = await platform.DeleteWeighRecordAsync(new PlatformBase.DeleteWeighRecordParams
                        {
                            WeighRecord = record,
                            Reason = I18NService.Translate(LangKeys._0_确认已作废或删除, Globalspace._currentUser.LoginId)
                        });
                        if (!deleteResult.Success)
                        {
                            MessageBox.Show(deleteResult.Message, I18NService.Translate(LangKeys.删除失败), MessageBoxButton.OK);
                            break;
                        }
                        deleted.Add(record.Bh);
                    }

                }

                var delRet = await db.WeighingRecords.Where(p => deleted.Contains(p.Bh)).ExecuteDeleteAsync();

                MessageBox.Show(delRet > 0
                    ? I18NService.Translate(LangKeys.删除成功_0_, I18NService.Translate(LangKeys._0_条记录, deleted.Count))
                    : I18NService.Translate(LangKeys.删除失败_0_, I18NService.Translate(LangKeys.未找到任何数据)),
                    I18NService.Translate(LangKeys.提示), MessageBoxButton.OK);
                Query();
            }
        }

        public void WeightRecordDataGridLoaded(object sender, RoutedEventArgs e)
        {
            _dataGrid = (DataGrid)sender;
        }

        public void RowCheckedChangedHandle(object sender, System.Windows.RoutedEventArgs e)
        {
            if (_allRowCheckboxProcess)
            {
                return;
            }
            var cbx = ((CheckBox)sender);
            if (cbx.DataContext is not WeighingRecord view)
            {
                return;
            }

            view.Checked = cbx.IsChecked.GetValueOrDefault();

            var checkedCount = WeighingRecordRows.Count(p => p.Checked);

            _allRowCheckbox.IsThreeState = checkedCount > 0 && checkedCount != WeighingRecordRows.Count;
            if (_allRowCheckbox.IsThreeState)
            {
                _allRowCheckbox.IsChecked = null;
            }
            else
            {
                _allRowCheckbox.IsChecked = checkedCount == WeighingRecordRows.Count;
            }

            //CanDeleteSelectedRows = checkedCount > 0;

        }


        public void AllRowCheckBox_Loaded(object sender, System.Windows.RoutedEventArgs e)
        {
            _allRowCheckbox = (CheckBox)sender;
        }

        public void AllRowCheckedChangedHandle(object sender, System.Windows.RoutedEventArgs e)
        {
            _allRowCheckboxProcess = true;
            var cbx = ((CheckBox)sender);
            cbx.IsThreeState = !cbx.IsChecked.HasValue;
            if (cbx.IsChecked != null && cbx.IsChecked.HasValue)
            {
                foreach (var row in WeighingRecordRows)
                {
                    row.Checked = cbx.IsChecked.GetValueOrDefault();
                }
            }
            _allRowCheckboxProcess = false;
        }

        public void WRecordSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (sender is DataGrid dg)
            {
                e.Handled = true;
                if (dg.SelectedItem is not WeighingRecord view)
                {
                    return;
                }

                var bh = view.Bh;
                if (!string.IsNullOrWhiteSpace(bh))
                {
                    var match = bh.Contains("X");
                    ButtonVisible = match ? Visibility.Collapsed : Visibility.Visible;
                    //if (_enableDeleteSelectedOfRole)
                    //{
                    //    EnableDeleteSelected = !match;
                    //}

                    SelectedRowRecord = view;
                }
            }
        }


        private WeighingRecordSearchForm CreateWeighingRecordSearchForm(List<DynamicPoundFieldItem> fields = null)
        {
            var by20Field = nameof(Common.Models.WeighingRecord.By20);
            var timeField = SelectedDateField ?? nameof(Common.Models.WeighingRecord.Jzrq);

            var searchForm = new WeighingRecordSearchForm
            {
                Page = CurrentIndex,
                Limit = PageCount
            };

            var queryObj = new Newtonsoft.Json.Linq.JObject
            {
                { by20Field, DyanmicPoundFieldItems.Any(p => p.Field == by20Field && p.IsColumnDisplay) },
                {nameof(Common.Models.WeighingRecord.IsFinish), _isFinished }
            };

            if (StartDate != null)
            {
                queryObj.Add($"{timeField}Start", StartDate.GetValueOrDefault().ToString("yyyy-MM-dd HH:mm:ss"));
            }
            if (EndDate != null)
            {
                queryObj.Add($"{timeField}End", EndDate.GetValueOrDefault().ToString("yyyy-MM-dd HH:mm:ss"));
            }

            foreach (var item in _importOrExportFields)
            {
                if (!item.Checked || string.IsNullOrWhiteSpace(item.Value))
                {
                    continue;
                }

                queryObj.Add(item.Field, item.Value);
            }
            searchForm.Filter = queryObj;
            return searchForm;
        }

        public async void QueryList()
        {
            Loading = true;
            try
            {
                var by20Field = nameof(Common.Models.WeighingRecord.By20);
                _importOrExportFields = DyanmicPoundFieldItems.Where(p => p.IsColumnDisplay && p.Field != by20Field).ToList();

                if (_importOrExportFields.Count == 0)
                {
                    MessageBoxExt.Alert(I18NService.Translate(LangKeys.请选择要显示的列));
                    return;
                }

                var searchForm = CreateWeighingRecordSearchForm();
                using var ctrl = new WeighingRecordController();
                var paged = await ctrl.Pages(searchForm);

                var list = AJAutoMapperService.Instance().Mapper.Map<List<Common.EF.Tables.WeighingRecord>, List<Common.Models.WeighingRecord>>(paged.Data);
                ////----------分页逻辑开始------
                DataCount = paged.TotalCount;//数据总数
                Pages = paged.TotalPages;//总页数

                ////----------分页逻辑结束------

                ////---------计算报表数据-------
                UnfinishedReportData = string.Empty;

                UnfinishedReportData += $" {I18NService.Translate(LangKeys.当页未完成_0_, paged.Data.Count(p => !p.IsFinish))}";

                ReportData = string.Empty;
                ReportData += $" {I18NService.Translate(LangKeys.当页总毛重_0_, AJUtil.ChineseRound(paged.Data.Sum(s => s.Mz)))} |";
                ReportData += $" {I18NService.Translate(LangKeys.当页总皮重_0_, AJUtil.ChineseRound(paged.Data.Sum(s => s.Pz)))} |";
                ReportData += $" {I18NService.Translate(LangKeys.当页总净重_0_, AJUtil.ChineseRound(paged.Data.Sum(s => s.Jz)))} |";
                ReportData += $" {I18NService.Translate(LangKeys.当页总实重_0_, AJUtil.ChineseRound(paged.Data.Sum(s => s.Sz)))} |";
                ReportData += $" {I18NService.Translate(LangKeys.当页总扣重_0_, AJUtil.ChineseRound(paged.Data.Sum(s => s.Kz)))}";

                WeighingRecordRows = new ObservableCollection<WeighingRecord>(list);

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, I18NService.Translate(LangKeys.查询错误), MessageBoxButton.OK);
            }
            finally
            {
                Loading = false;
                SetBtns();
            }
        }

        public void OpenWeighLineChartDialog()
        {
            if (SelectedRowRecord == null)
            {
                MessageBoxExt.Alert(I18NService.Translate(LangKeys.请选择一条记录));
                return;
            }

            var viewModel = new WeighLineChartViewModel(SelectedRowRecord);
            windowManager.ShowDialog(viewModel);
        }

        public void PrintList()
        {
            if ((WeighingRecordRows?.Count).GetValueOrDefault() == 0)
            {
                MessageBoxExt.Alert(I18NService.Translate(LangKeys.当前查询列表为空));
                return;
            }

            //设置列宽
            var columnWidths = new List<double>();

            foreach (var field in _importOrExportFields)
            {
                if (field.Field == nameof(Common.Models.WeighingRecord.Bh)
                    || field.Field == nameof(Common.Models.WeighingRecord.Bz)
                    || field.Field == nameof(Common.Models.WeighingRecord.EditReason)
                    || field.Field.Contains("rq"))
                {
                    columnWidths.Add(120);
                    continue;
                }
                columnWidths.Add(80);
            }

            var ht = new Common.Views.ListHeaderTemplate();
            var headerTemplate = XamlWriter.Save(ht);
            #region 替换总计关键字
            headerTemplate = headerTemplate.Replace("@Company", _mainSettings.Settings["CompanyName"].Value);
            headerTemplate = headerTemplate
                .Replace("@StartDate", StartDate.GetValueOrDefault().ToString("yyyy/MM/dd HH:mm"))
                .Replace("@EndDate", EndDate.GetValueOrDefault().ToString("yyyy/MM/dd HH:mm"));

            var allTxt = I18NService.Translate(LangKeys.全部);

            var carNoFilter = DyanmicPoundFieldItems.FirstOrDefault(p => p.Field == nameof(Common.Models.WeighingRecord.Ch) && !string.IsNullOrWhiteSpace(p.Value));
            headerTemplate = headerTemplate.Replace("@PlateNo", carNoFilter?.Value ?? allTxt);


            var khFilter = DyanmicPoundFieldItems.FirstOrDefault(p => p.Field == nameof(Common.Models.WeighingRecord.Kh) && !string.IsNullOrWhiteSpace(p.Value));
            headerTemplate = headerTemplate.Replace("@Customer", khFilter?.Value ?? allTxt);

            var goodsFilter = DyanmicPoundFieldItems.FirstOrDefault(p => p.Field == nameof(Common.Models.WeighingRecord.Wz) && !string.IsNullOrWhiteSpace(p.Value));
            headerTemplate = headerTemplate.Replace("@Goods", goodsFilter?.Value ?? allTxt);

            var totalJz = AJUtil.ChineseRound(WeighingRecordRows.Sum(p => p.Jz));

            headerTemplate = headerTemplate.Replace("@TotalWeighingCount", WeighingRecordRows.Count.ToString());
            headerTemplate = headerTemplate.Replace("@TotalJz", $"{totalJz} {WeighingUnit}");

            var totalSz = AJUtil.ChineseRound(WeighingRecordRows.Sum(p => p.Sz));
            headerTemplate = headerTemplate.Replace("@TotalSz", $"{totalSz} {WeighingUnit}");

            var totalMz = AJUtil.ChineseRound(WeighingRecordRows.Sum(p => p.Mz));
            headerTemplate = headerTemplate.Replace("@TotalMz", $"{totalMz} {WeighingUnit}");

            var totalPz = AJUtil.ChineseRound(WeighingRecordRows.Sum(p => p.Pz));
            headerTemplate = headerTemplate.Replace("@TotalPz", $"{totalPz} {WeighingUnit}");

            #endregion

            var table = _dataGrid.ToTable();

            var loadingDialog = new AJCommonLoadingDialogViewModel(I18NService.Translate(LangKeys.正在构建打印任务), () =>
            {
                var result = new ProcessResult();
                try
                {
                    var printControl = PrintControlFactory.Create(table, columnWidths, headerTemplate);
                    printControl.ShowPrintPreview();
                    result.SetSuccess();
                }
                catch (Exception e)
                {
                    result.SetError(e.Message);
                }

                return Task.FromResult(result);
            });

            var dialogRet = windowManager.ShowDialog(loadingDialog);

            MessageBoxExt.Alert(loadingDialog.Result.Success
                ? I18NService.Translate(LangKeys.打印任务构建成功) : loadingDialog.Result.Message);

        }

        public void ExportList()
        {
            if ((WeighingRecordRows?.Count).GetValueOrDefault() == 0)
            {
                MessageBoxExt.Alert(I18NService.Translate(LangKeys.当前查询列表为空));
                return;
            }

            //使用DataTable数据新建excle表格
            Workbook workbook = new Workbook();
            Worksheet worksheet = workbook.Worksheets[0];
            worksheet.Name = I18NService.Translate(LangKeys.称重记录);

            ImportTableOptions importOptions = new ImportTableOptions();
            importOptions.IsFieldNameShown = true;
            importOptions.IsHtmlString = true;

            var table = _dataGrid.ToTable();

            worksheet.Cells.ImportData(table, 0, 0, importOptions);

            #region 增加表头、格式

            Aspose.Cells.Style blodStyle = workbook.CreateStyle();
            blodStyle.Font.IsBold = true;
            StyleFlag flag = new StyleFlag();
            flag.FontBold = true;

            Aspose.Cells.Style headerStyle = workbook.CreateStyle();
            headerStyle.Font.IsBold = true;
            headerStyle.Font.Size = 16;
            headerStyle.HorizontalAlignment = TextAlignmentType.Center;

            worksheet.Cells.Rows[0].ApplyStyle(blodStyle, flag);

            worksheet.Cells.InsertRows(0, 5);

            worksheet.Cells.Merge(0, 0, 1, (table.Columns.Count > 8) ? table.Columns.Count : 8);
            worksheet.Cells["A1"].PutValue(_mainSettings.Settings["CompanyName"].Value + I18NService.Translate(LangKeys.称重明细列表));
            worksheet.Cells["A1"].SetStyle(headerStyle);
            worksheet.Cells["A2"].PutValue(I18NService.Translate(LangKeys.统计日期));
            worksheet.Cells["A2"].SetStyle(blodStyle);
            worksheet.Cells.Merge(1, 1, 1, 5);
            worksheet.Cells["B2"].PutValue(((DateTime)StartDate).ToString("yyyy/MM/dd") + " ~ " + ((DateTime)EndDate).ToString("yyyy/MM/dd"));
            worksheet.Cells["G2"].PutValue(I18NService.Translate(LangKeys.重量单位));
            worksheet.Cells["G2"].SetStyle(blodStyle);
            worksheet.Cells["H2"].PutValue(WeighingUnit);
            worksheet.Cells["A3"].PutValue(I18NService.Translate(LangKeys.车号));
            worksheet.Cells["A3"].SetStyle(blodStyle);

            var allTxt = I18NService.Translate(LangKeys.全部);

            var carNoFilter = DyanmicPoundFieldItems.FirstOrDefault(p => p.Field == nameof(Common.Models.WeighingRecord.Ch) && !string.IsNullOrWhiteSpace(p.Value));
            worksheet.Cells["B3"].PutValue(carNoFilter?.Value ?? allTxt);

            worksheet.Cells["D3"].PutValue(I18NService.Translate(LangKeys.客户));
            worksheet.Cells["D3"].SetStyle(blodStyle);
            var khFilter = DyanmicPoundFieldItems.FirstOrDefault(p => p.Field == nameof(Common.Models.WeighingRecord.Kh) && !string.IsNullOrWhiteSpace(p.Value));
            worksheet.Cells["E3"].PutValue(khFilter?.Value ?? allTxt);

            worksheet.Cells["G3"].PutValue(I18NService.Translate(LangKeys.物资));
            worksheet.Cells["G3"].SetStyle(blodStyle);
            var goodsFilter = DyanmicPoundFieldItems.FirstOrDefault(p => p.Field == nameof(Common.Models.WeighingRecord.Wz) && !string.IsNullOrWhiteSpace(p.Value));
            worksheet.Cells["H3"].PutValue(goodsFilter?.Value ?? allTxt);


            worksheet.Cells["A4"].PutValue(I18NService.Translate(I18NService.Translate(LangKeys.总车次)));
            worksheet.Cells["A4"].SetStyle(blodStyle);
            worksheet.Cells["B4"].PutValue(table.Rows.Count);
            worksheet.Cells["D4"].PutValue(I18NService.Translate(LangKeys.总净重));
            worksheet.Cells["D4"].SetStyle(blodStyle);
            worksheet.Cells["E4"].PutValue(AJUtil.ChineseRound(WeighingRecordRows.Sum(p => p.Jz)));

            var szFilter = DyanmicPoundFieldItems.FirstOrDefault(p => p.Field == nameof(Common.Models.WeighingRecord.Sz));

            if (szFilter != null)
            {
                worksheet.Cells["G4"].PutValue(I18NService.Translate(LangKeys.总实重));
                worksheet.Cells["G4"].SetStyle(blodStyle);
                worksheet.Cells["H4"].PutValue(AJUtil.ChineseRound(WeighingRecordRows.Sum(p => p.Sz)));
            }

            worksheet.AutoFitColumns();
            #endregion

            workbook.Save(Globalspace._weighingRecordTempPath, SaveFormat.Xlsx);

            //删掉aspose的试用版信息，删掉临时文件
            XSSFWorkbook book;
            using (FileStream file = new FileStream(Globalspace._weighingRecordTempPath, FileMode.Open, FileAccess.Read))
            {
                book = new XSSFWorkbook(file);
            }
            //book.RemoveSheetAt(1);
            System.IO.File.Delete(Globalspace._weighingRecordTempPath);

            //打开保存文件对话框，保存称重记录
            var fileDialog = new Microsoft.Win32.SaveFileDialog
            {
                CreatePrompt = true,
                OverwritePrompt = true,
                AddExtension = true,
                DefaultExt = ".xlsx",
                Filter = $"{I18NService.Translate(LangKeys.excel文件)}（.xlsx）|*.xlsx",
                FileName = $"{I18NService.Translate(LangKeys.称重记录)}_{DateTime.Now.ToString("yyyyMMdd")}",
            };

            if (fileDialog.ShowDialog().GetValueOrDefault())
            {
                FileStream file = new FileStream(fileDialog.FileName, FileMode.Create);
                book.Write(file);
                file.Close();
                book.Close();
                MessageBoxExt.Alert(I18NService.Translate(LangKeys.导出成功_0_文件路径_1_, I18NService.Translate(LangKeys.称重记录), fileDialog.FileName));
            }
        }


        public void OpenPzReport()
        {
            if (SelectedRowRecord == null)
            {
                MessageBoxExt.Alert(I18NService.Translate(LangKeys.请选择一条记录));
                return;
            }

            var viewModel = new PzReportViewModel(this.windowManager, SelectedRowRecord);
            this.windowManager.ShowWindow(viewModel);

        }

        /// <summary>
        /// 一键补传所有
        /// </summary>
        public async void ReUploadAll()
        {
            var progressView = new ReuploadAllProgressViewModel(windowManager, NotUploadedRecords);
            windowManager.ShowDialog(progressView);

            using var db = AJDatabaseService.GetDbContext();

            var pages = await db.WeighingRecords.Where(p => p.IsUpload == false).AsNoTracking().ToListAsync();

            NotUploadedRecords = AJAutoMapperService.Instance().Mapper.Map<List<Common.EF.Tables.WeighingRecord>, List<Common.Models.WeighingRecord>>(pages);

            ReUploadButtonVisible = NotUploadedRecords.Count > 0
                 ? Visibility.Visible : Visibility.Collapsed;
        }

        public void ReUpload()
        {
            if (SelectedRowRecord == null)
            {
                MessageBoxExt.Alert(I18NService.Translate(LangKeys.请选择一条记录));
                return;
            }

            var obj
                = AJUtil.TryGetJSONObject<Common.Models.WeighingRecord>(AJUtil.AJSerializeObject(SelectedRowRecord));

            if (Common.Platform.PlatformManager.Instance.Current is PlatformBase platform)
            {
                if (platform.IsDefault)
                {
                    return;
                }
                var mianSetting = Common.Utility.SettingsHelper.AWSV2Settings;
                Task.Run(async () =>
                {
                    var result = await platform.UploadWeighRecordAsync(new PlatformBase.UploadWeighRecordParams
                    {
                        MainSettings = mianSetting,
                        LPRSvc = null,
                        WeighRecord = obj
                    });

                    if (!result.Success)
                    {
                        MessageBox.Show(result.Message);
                    }
                    MessageBox.Show(result.Success ? I18NService.Translate(LangKeys.上传成功) : result.Message, I18NService.Translate(LangKeys.第一次称重上传提示), MessageBoxButton.OK);
                    if (obj.WeighingTimes == 1)
                    {
                        // 上传第二次
                        obj.WeighingTimes = 2;
                        obj.Mz = SelectedRowRecord.Pz;
                        obj.Weigh2Name = SelectedRowRecord.WeighName;
                        obj.Mzrq = SelectedRowRecord.Pzrq;
                        obj.Jz = SelectedRowRecord.Mz - SelectedRowRecord.Pz;
                        obj.Jzrq = DateTime.Now;

                        result = await platform.UploadWeighRecordAsync(new PlatformBase.UploadWeighRecordParams
                        {
                            MainSettings = mianSetting,
                            LPRSvc = null,
                            WeighRecord = obj
                        });

                        if (result.Success)
                        {
                            using var db = AJDatabaseService.GetDbContext();
                            var id = obj.AutoNo;
                            var ch = obj.Ch;
                            db.WeighingRecords.Where(p => p.AutoNo == id && p.Ch == ch).ExecuteUpdate(sp => sp.SetProperty(p => p.IsUpload, true));
                        }

                        MessageBox.Show(result.Success ? I18NService.Translate(LangKeys.上传成功) : result.Message, I18NService.Translate(LangKeys.第二次称重上传提示), MessageBoxButton.OK);
                    }
                });
            }

        }

        public void UpdateSelected()
        {
            if (SelectedRowRecord == null)
            {
                MessageBoxExt.Alert(I18NService.Translate(LangKeys.请选择一条记录));
            }
            else
            {
                var reason = I18NService.Translate(LangKeys.管理员权限修改);

                if (Globalspace._currentUser.LoginId != "admin")
                {
                    var curRolePermission = Globalspace._currentUser.Permission ?? string.Empty;

                    if (curRolePermission.Contains("修改需要密码授权"))
                    {
                        var vm = new Common.ViewModels.PasswordViewModel(Globalspace._currentUser.LoginId, Common.ViewModels.PasswordConfirmType.用户授权);

                        if (!windowManager.ShowDialog(vm).GetValueOrDefault(true))
                        {
                            return;
                        }

                        var promptDialog = new AJPromptDialogViewModel
                        {
                            Title = I18NService.Translate(LangKeys.请输入修改原因),
                            Required = true,
                            SingleLine = false,
                            ConfirmText = I18NService.Translate(LangKeys.确定),
                            Type = ControlStatusType.Info,
                        };

                        var promptResult = this.windowManager.ShowDialog(promptDialog);

                        if (!promptResult.GetValueOrDefault())
                        {
                            return;
                        }
                        reason = promptDialog.Text;
                    }
                }

                var record
                = AJUtil.TryGetJSONObject<Common.Models.WeighingRecord>(AJUtil.AJSerializeObject(SelectedRowRecord));


                record.EditReason = reason;
                var validator = new WeighingRecordViewModelValidator();
                var validatorAdapter = new FluentModelValidator<WeighingRecordViewModel>(validator);

                var viewModel = new WeighingRecordViewModel(validatorAdapter, _fieldsSource,
                    DyanmicPoundFieldItems,
                    this.windowManager, record);
                var result = this.windowManager.ShowDialog(viewModel);
                if (result.GetValueOrDefault(true))
                {
                    QueryList();
                    SetBtns();
                    MessageBoxExt.Alert(I18NService.Translate(LangKeys.修改记录完成));
                }
            }
        }

        public void DeleteSelected()
        {
            //try
            //{
            //    if (SelectedRecrod == null)
            //    {
            //        StatusBar = "请选择一条记录";
            //        return;
            //    }

            //    {
            //        //var vm = new PasswordViewModel(windowManager, 3);
            //        bool? result = true;// windowManager.ShowDialog(vm);

            //        if (result.GetValueOrDefault(true))
            //        {
            //            var Bh = SelectedRecrod.Row.ItemArray[_BhColumnIndex].ToString();
            //            var Record = WList.Find(w => w.Bh == Bh);

            //            if (DelBtnText == "作废选中")
            //            {
            //                SQLDataAccess.DeleteWeighingRecord((WeighingRecord)Record);
            //                StatusBar = "选中记录已删除";
            //                DelBtnText = "取消作废";
            //            }
            //            else//取消作废
            //            {
            //                SQLDataAccess.ResetWeighingRecord((WeighingRecord)Record);
            //                StatusBar = "选中记录已恢复";
            //                DelBtnText = "作废选中";
            //            }

            //            QueryList();
            //            SetBtns();

            //        }
            //    }
            //}
            //catch (Exception ex)
            //{
            //    log.Info("DeleteSelected error:" + ex.Message);
            //}

        }

        #region 分页逻辑以及属性

        /// <summary>
        /// 索引信息集合
        /// </summary>
        public ObservableCollection<PagerHandle> Indexs { get; set; } = new ObservableCollection<PagerHandle>();



        public ObservableCollection<ComboItem> PageSizeItems { get; set; }

        ComboItem _SelectedPageSizeItems;
        public ComboItem SelectedPageSizeItems
        {
            get
            {
                return _SelectedPageSizeItems;
            }
            set
            {
                if (value != null)
                {
                    _SelectedPageSizeItems = value;
                    PageCount = int.Parse(_SelectedPageSizeItems.Value.ToString());
                    Query();
                }
            }
        }

        /// <summary>
        /// 当前选中的索引信息
        /// </summary>
        public int CurrentIndex { get; set; } = 1;
        /// <summary>
        /// 页总数
        /// </summary>
        public int Pages { get; set; }
        /// <summary>
        /// 有效的索引按钮个数，不包含（...，最有一页这2个按钮）
        /// </summary>
        public int IndexButs { get; set; } = 3;
        /// <summary>
        /// 一页显示的行数
        /// </summary>
        public int PageCount { get; set; } = 1;
        /// <summary>
        /// 数据的总数
        /// </summary>
        public int DataCount { get; set; }


        public void LeftSide(object indexStr)
        {

            var moveIndex = CurrentIndex - 1;
            if (moveIndex < 1) return;

            CurrentIndex = moveIndex;

            SetBtns();
            SelectedPage(moveIndex.ToString());

        }

        public void RightSide(object indexStr)
        {
            var moveIndex = CurrentIndex + 1;
            if (moveIndex > Pages) return;


            CurrentIndex = moveIndex;

            SetBtns();
            SelectedPage(moveIndex.ToString());

        }

        public void SelectedPage(object indexStr)
        {
            string str = indexStr.ToString();

            if (string.IsNullOrEmpty(str)) return;

            if (str != "...")
            {
                CurrentIndex = int.Parse(str);
            }

            if (str == "...")
            {
                var maxIndex = Indexs.Where(p => p.IndexStr != "..." && p.IndexStr != Pages.ToString()).Max(p => int.Parse(p.IndexStr));
                CurrentIndex = maxIndex;
                SetBtns();
            }
            else
            {
                var indexInfo = Indexs.FirstOrDefault(p => p.IndexStr == str);

                QueryList();
                if (CurrentIndex == Pages)
                {
                    SetBtns();
                }
            }

        }

        private void SetBtns()
        {
            Indexs.Clear();

            if (CurrentIndex < 1 || CurrentIndex > Pages) return;

            if (Pages <= IndexButs)
            {
                for (int i = 1; i <= Pages; i++)
                {
                    if (i == CurrentIndex)
                    {
                        Indexs.Add(new PagerHandle() { IndexStr = i.ToString() });
                        continue;
                    }
                    Indexs.Add(new PagerHandle() { IndexStr = i.ToString() });
                }

            }
            else
            {
                int i = CurrentIndex;

                for (; i <= Pages; i++)
                {
                    if (i - CurrentIndex >= IndexButs) break;

                    if (i == CurrentIndex)
                    {
                        Indexs.Add(new PagerHandle() { IndexStr = i.ToString() });
                        continue;
                    }
                    Indexs.Add(new PagerHandle() { IndexStr = i.ToString() });
                }
                if (i < Pages)
                {
                    Indexs.Add(new PagerHandle() { IndexStr = "..." });
                    Indexs.Add(new PagerHandle() { IndexStr = Pages.ToString() });
                }
                else if (Indexs.Count < IndexButs)//如果没有预定的IndexButs个按钮，那么就要补齐少的
                {
                    int minIdex = Indexs.Min(p => int.Parse(p.IndexStr));
                    for (int j = Indexs.Count; j < IndexButs; j++)
                    {
                        minIdex--;
                        Indexs.Insert(0, new PagerHandle() { IndexStr = (minIdex).ToString() });
                    }
                }
            }
        }

        public void Query()
        {
            CurrentIndex = 1;
            QueryList();

        }

        #endregion

        public async void PrintSelected()
        {
            if (SelectedRowRecord == null)
            {
                MessageBoxExt.Alert(I18NService.Translate(LangKeys.请选择一条记录));
            }
            else
            {
                SelectedRowRecord.Dyrq = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

                var wss = new Workbook(Globalspace._weightFormTemplatePath).Worksheets;
                var tplIndex = _mainSettings.Settings["PrintTemplate"].TryGetInt(1);
                var sheet = wss.ElementAtOrDefault(tplIndex - 1);
                if (sheet == null)
                {
                    MessageBox.Show(I18NService.Translate(LangKeys.磅单excel未配置任何打印模板), I18NService.Translate(LangKeys.打印失败), MessageBoxButton.OK);
                    return;
                }

                var result = await Common.Utility.PrintHelper.PrintWeighRecordAsync(SelectedRowRecord, _mainSettings,

                    SelectedRowRecord.WeighingTimes == 1 ? PrintWeighType.FirstWeighing : PrintWeighType.SecondWeighing);

                if (!result.Success || result.Message != "ok")
                {
                    MessageBox.Show(result.Message, I18NService.Translate(LangKeys.打印失败), MessageBoxButton.OK);
                }
            }
        }

        public void InsertItem()
        {
            var validator = new WeighingRecordViewModelValidator();
            var validatorAdapter = new FluentModelValidator<WeighingRecordViewModel>(validator);

            var viewModel = new WeighingRecordViewModel(validatorAdapter, _fieldsSource,
                    DyanmicPoundFieldItems,
                    this.windowManager, null);
            var result = this.windowManager.ShowDialog(viewModel);
            if (result.GetValueOrDefault(true))
            {
                QueryList();
                SetBtns();
                MessageBoxExt.Alert(I18NService.Translate(LangKeys.新增记录完成));
            }
        }

        public async void OpenPicFolder()
        {

            PicListViewModel.Show(SelectedRowRecord);

        }
    }
}
